import re


# 只含文本信息，不含群号、发送者QQ号等等
class MessageParse:
    # 打算将cq码提取出来之后，将剩下的消息按空格分隔，装入到msg_list里
    # 或者将分隔之后的第一个作为命令的名称（command_name），将剩下的作为参数（command_data），参数也应该是一个列表
    def __init__(self, text):
        print('text = ', text)
        print("\n")
        self.isAtMe = False
        self.cqList = []
        self.msgList = []
        self.msg = ''  # 纯文本信息
        self.command_name = ''
        self.command_data = []  # 或者说使用字典？
        self.parseMsg(text)

    def parseMsg(self, text):
        r = re.compile(r"\[CQ:.*?\]", re.M | re.I)
        t = r.findall(text)
        if t:
            self.getCQCodeList(t)
            # 利用sub去除字符串中的cq码，只剩下纯文本消息
            text = r.sub('', text)
            print('去除cq码后的text = ', text)
        # 处理纯文本消息，利用空格进行分隔
        print('分隔前的text = ', text)
        text_list_temp = text.split(' ')
        print('text_list_temp = ', text_list_temp)
        # 去除多余的空格
        text_list = []
        for i in text_list_temp:
            if i != '':
                text_list.append(i)
        # 保存消息和消息列表
        self.msg = text
        self.msgList = text_list
        # 按照猜想，分别保存命令和参数
        print('text_list = ', text_list)
        if len(text_list) > 0:
            self.command_name = text_list[0] or ''
            self.command_data = text_list[1:] or []

    def getCQCodeList(self, mylist):
        r = re.compile(r"\[CQ:(.*)?\]", re.M | re.I)
        # 纯文本的cq码的列表
        for i in mylist:
            # 以 [CQ:at,qq=3265107863] 为例，获取at,qq=3265107863
            t = r.match(i).group(1)
            a = t.split(',')  # ['at', 'qq=3265107863']
            cqcode = dict()
            cqcode["type"] = a[0]  # type, 即'at'
            temp_dict = dict()
            for j in a[1:]:  # j是'qq=3265107863'这样的
                tt = j.split("=")  # ['qq', '3265107863']
                temp_dict[tt[0]] = tt[1]  # {'qq': '3265107863'}
            cqcode['data'] = temp_dict  # 组装完成了一个cqcode
            self.cqList.append(cqcode)
            if not self.isAtMe:
                if a[0] == 'at' and temp_dict.get('qq') == '2230722008':
                    self.isAtMe = True

    def __str__(self):
        mystr = "isAtMe: \n" + str(self.isAtMe) + '\n' \
                + "cqList：\n" + str(self.cqList) + '\n' \
                + "msgList: \n" + ''.join(self.msgList) + '\n' \
                + "msg: \n" + self.msg + '\n' \
                + "command_name: \n" + self.command_name + '\n' \
                + "command_data: \n" + ','.join(self.command_data) + '\n'
        return mystr
